import { getText } from "../util/http-utils.ts";
import * as cheerio from "cheerio";
import type { GenericFileInfo } from "@common/spider-types.ts";
import path from "node:path";

/**
 * 获取Nacos稳定版本列表
 */
export async function getNacosStableVersions(): Promise<GenericFileInfo[]> {
  const resp = await getText("https://nacos.io/download/nacos-server/");
  const $ = cheerio.load(resp.data);
  const versions: GenericFileInfo[] = [];
  $("#稳定版本")
    .nextAll("table")
    .each((_, el) => {
      const row0 = $(el).find("tbody tr").eq(0);
      const cells = row0.find("td");
      const version = cells.eq(0).text().trim();
      if (version.toLowerCase().includes("beta") || version.toLowerCase().includes("alpha") || version.toLowerCase().includes("rc")) {
        return;
      }
      const $a = cells.eq(1).find("a");
      const downloadUrl = $a.attr()?.href;
      if (downloadUrl) {
        versions.push({
          version,
          name: path.basename(downloadUrl),
          url: downloadUrl,
        });
      }
    });

  return versions;
}
